//
//  SearchViewController.m
//  ClinicalCollections
//
//  Created by janakiraman gopinath on 1/20/13.
//  Copyright (c) 2013 GOPI. All rights reserved.
//

#import "SearchViewController.h"
#import "CommonAPI.h"

@interface SearchViewController () <UITableViewDataSource, UITableViewDelegate,UISearchBarDelegate,
UIScrollViewDelegate>
@property (nonatomic, weak) UISearchBar *uiSearchBar;
@property (nonatomic, weak) UILabel *uiLabel;
@property (nonatomic, strong) NSString *searchString;
@property (nonatomic, strong) NSArray *searchList;
@property (nonatomic, strong) UIActivityIndicatorView *spinner;
@property (nonatomic, strong) Search *search;
@property (nonatomic, strong) NSMutableArray *filteredListContent;
@property (nonatomic) BOOL filterSet;
@property (nonatomic, strong) UIManagedDocument *database;
@property (nonatomic) BOOL searchEnable;
@property (nonatomic, strong) NSString *nctID;
@end


@implementation SearchViewController
@synthesize uiSearchBar = _uiSearchBar;
@synthesize uiTableView = _uiTableView;
@synthesize uiLabel = _uiLabel;
@synthesize database = _database;
@synthesize spinner = _spinner;
@synthesize search = _search;
@synthesize filteredListContent = _filteredListContent;
@synthesize filterSet = _filterSet;
@synthesize searchEnable = _searchEnable;
@synthesize nctID = _nctID;
#pragma mark -- LifeCycle methods

- (void) initMethods:(BOOL) reset
{
    if (reset) {
        [self.uiTableView setUserInteractionEnabled:YES];
        [self.uiTableView setHidden:NO];
        [self.uiTableView setDelegate:self];
        [self.uiTableView setDataSource:self];
    }
    else {
        [self.uiTableView setUserInteractionEnabled:NO];
        [self.uiTableView setHidden:YES];
        [self.uiTableView setDelegate:nil];
        [self.uiTableView setDataSource:nil];
    }
}
- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self initMethods:NO];
    
    [[DatabaseHelper class] openDatabase:nil
                                  reopen:NO
                              usingBlock:^(UIManagedDocument *database){
                                  self.database = database;
                                  self.filterSet = NO;
                                  self.searchList = [Search fetchSearchStringWithSearchType:[self restorationIdentifier]
                                                                   inManagedDocumentContext:self.database.managedObjectContext];
                                  
                                  [[self uiTableView] setFrame:CGRectMake(10, 220, 300, 400)];
                                  [self initMethods:YES];
                                  [[self uiTableView] reloadData];
                                  ClinicalCollectionsViewController *ccvc =
                                  [[CommonAPI class] targetViewControllerFrom:self
                                                                      forPath:NA
                                                                         side:RIGHT
                                                      returningViewController:CLINICALCOLLECTIONSVIEWCONTROLLER ];
                                  [ccvc hideSearchBar:YES];
                                  // Clear search text if any present from previous search and dismiss the
                                  // Keyboard
                                  
                                  [[CommonAPI class] clearKeyboardAndSearchText:ccvc];
                                  [[CommonAPI class] setupNotification:RECENT_EVENTS
                                                                   for:self
                                                              selector:@selector(recentNotification:)];
                              }];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView *baseView = [self view];
    NSArray *childViews = [baseView subviews];
    
    for (UIView *v in  childViews) {
        if ([v isKindOfClass:[UISearchBar class]] &&
            [[v restorationIdentifier] isEqualToString:@BAR_FOR_SEARCH]) {
            self.uiSearchBar = (UISearchBar *) v;
            
            [self.uiSearchBar setDelegate:self];
        }
        if ([v isKindOfClass:[UIScrollView class]]) {
            id tv = [[v subviews] objectAtIndex:0];
            if ([tv isKindOfClass:[UITableView class]] &&
                [[tv restorationIdentifier] isEqualToString:@SEARCH_TABLE_VIEW]) {
                self.uiTableView = (UITableView *) tv;
                [self initMethods:YES];
            }
        }
        if ([v isKindOfClass:[UITableView class]] &&
            [[v restorationIdentifier] isEqualToString:@SEARCH_TABLE_VIEW]) {
            self.uiTableView = (UITableView *) v;
             [self initMethods:YES];
        }
        if ([v isKindOfClass:[UILabel class]] &&
            [[v restorationIdentifier] isEqualToString:@TITLE_LABEL])
            self.uiLabel = (UILabel *) v;
    }
    
}

#pragma mark -- getter setter methods

- (NSMutableArray *) filteredListContent {
    
    if (!_filteredListContent) {
        _filteredListContent = [[NSMutableArray alloc] initWithCapacity:MAX_CAPACITY];
    }
    return _filteredListContent;
}

- (void) recentNotification:(NSNotification *) notification
{
    NSString *nctID = [[notification.object componentsSeparatedByString:@","] objectAtIndex:0];
    self.searchString= [[notification.object componentsSeparatedByString:@","] objectAtIndex:1];
    self.nctID = nctID;
    
    ClinicalTrialGov *clinGov = [[CommonAPI class] clinicalTrialGov:nctID fromSearch:self.search];
    NSLog(@"Notifiation %@" , notification.object);
    self.searchEnable = YES;
    if (clinGov == nil || !clinGov)
        self.search = [[ClinicalTrialGov class] SearchForClinicalTrialGov:nctID
                                                                  context:[[DatabaseHelper class] database].managedObjectContext];
     [self performSegueWithIdentifier:@SEGUE_MAIN sender:self];
}

- (UIActivityIndicatorView *)spinner {
    if (!_spinner) {
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            _spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
            _spinner.center = CGPointMake(self.uiTableView.frame.size.width/2, self.uiTableView.frame.size.height/2);
            _spinner.frame = CGRectMake(_spinner.frame.origin.x - 40, _spinner.frame.origin.y - 40, 80, 80);
            _spinner.backgroundColor = [UIColor whiteColor];
            _spinner.color = [UIColor redColor];
            [self.uiTableView addSubview:_spinner];
        } else {
            _spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        }
    }
    return _spinner;
}




#pragma mark - SearchBarDelegate

- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    [self.uiSearchBar resignFirstResponder];
    self.searchString = self.uiSearchBar.text;
    
  //  UIBarButtonItem * barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.spinner];

    [self.spinner startAnimating];
   // [[self navigationItem] setRightBarButtonItem:barButtonItem];
    //[self initMethods:NO];
    
    [[CommonAPI class] download:^{
        
        // Either Fetch from database or go out to clinicalcollections to fetch
        // the data
        
        self.search = [Search setSearchStringWithSearchType:(NSString *)[self restorationIdentifier]
                                   inManagedDocumentContext:self.database.managedObjectContext
                                          usingSearchString:(NSString *) self.uiSearchBar.text
                                                   recrType:@"All"];
        [[CommonAPI class] main:^{
            
            [[DatabaseHelper class] updateDatabase:nil usingBlock:^(void) {
            }];
            self.uiSearchBar.text = @"";
            [self performSegueWithIdentifier:@SEGUE_MAIN sender:self];

        }];
    }];
    
    
    
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
    [self filterContentForSearchText:searchText];
    
}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    
    id vc = [segue destinationViewController];
    
    ((GenericTableViewController *) vc).search = self.search;
    ((GenericTableViewController *) vc).title = self.searchString;
    self.search = [Search updateSearch:self.search withLastAccessedDate:[NSDate dateWithTimeIntervalSinceNow:0] usingContext:self.database.managedObjectContext];
    [self.uiTableView reloadData];
    [[DatabaseHelper class] updateDatabase:nil usingBlock:^(void) {
        
        
    }];
    ClinicalCollectionsViewController *ccvc = [[CommonAPI class] targetViewControllerFrom:self
                                                                                  forPath:NA
                                                                                     side:RIGHT
                                                                  returningViewController:CLINICALCOLLECTIONSVIEWCONTROLLER];
    ccvc.search = self.search;
    
    if (self.searchEnable) {
        ((GenericTableViewController *) vc).filterSet = YES;
        NSDictionary *tempDictionary = [[CommonAPI class] searchData:self.search
                                            searchText:self.nctID];
        [((GenericTableViewController *) vc).filteredListContent addEntriesFromDictionary:tempDictionary];
        self.searchEnable = NO;
    }
    self.uiSearchBar.text = @"";
    [self.spinner stopAnimating];
    
    [[CommonAPI class] removeNotification:RECENT_EVENTS
                                      for:self];
}
#pragma mark - TableViewDataSource

- (void) tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
 forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        NSString *searchString;
        
        if (self.filterSet)
            searchString = [self.filteredListContent objectAtIndex:indexPath.row];
        else
            searchString = [[self.searchList objectAtIndex:indexPath.row] searchString];
        
        [Search deleteSearchStringWithSearchType:(NSString *)self.restorationIdentifier
                        inManagedDocumentContext:self.database.managedObjectContext
                               usingSearchString:searchString];
        [[CommonAPI class] removeRecentsSearchString:searchString];
        if (self.filterSet) {
            [self.filteredListContent removeObjectAtIndex:indexPath.row];
        }
        [[DatabaseHelper class] updateDatabase:nil usingBlock:^(void) {
           
            self.searchList = [Search fetchSearchStringWithSearchType:[self restorationIdentifier]
                                             inManagedDocumentContext:self.database.managedObjectContext];
            [self.uiTableView reloadData];
        }];
    }
}
- (void) tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.uiTableView cellForRowAtIndexPath:indexPath];
    self.searchString = cell.textLabel.text;
    
    self.search = [Search setSearchStringWithSearchType:(NSString *)[self restorationIdentifier]
                               inManagedDocumentContext:self.database.managedObjectContext
                                      usingSearchString:(NSString *) self.searchString
                                               recrType:@"All"];
    
    [self performSegueWithIdentifier:@SEGUE_MAIN sender:self];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.filterSet)
        return self.filteredListContent.count;
    else
        return self.searchList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @CLINICAL_COLLECTIONS_STRING;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    
    if (self.filterSet)
        cell.textLabel.text = [self.filteredListContent objectAtIndex:indexPath.row];
    
    else
        cell.textLabel.text = [[self.searchList objectAtIndex:indexPath.row] searchString];
    
    return cell;
}
#pragma mark -
#pragma mark Content Filtering

- (void)filterContentForSearchText:(NSString*)searchText
{
    NSArray *tempArray = [[NSArray alloc] initWithArray:self.filteredListContent];
	[self.filteredListContent removeAllObjects]; // First clear the filtered array.
	
    self.filterSet = NO;
	
	for (Search *searchList in self.searchList) {
        NSString *searchString = [searchList searchString];
        
        BOOL hit =  [[CommonAPI class] searchTextInString:searchString
                                               searchText:searchText];
        if (hit) {
            [self.filteredListContent addObject:searchString];
            self.filterSet = YES;
        }
	}
    // If the contents are the same dont reload the data
    // Also make sure some hit in the search string use self.filterSet bool variable
    
    if (self.filterSet && ![tempArray isEqualToArray:self.filteredListContent]) {
        [self.uiTableView reloadData];
    }
    else if (!self.filterSet && ![self.filteredListContent count]) {
        self.filterSet = YES;
        [self.uiTableView reloadData];
    }
    
}

@end
